package wechat;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.Configuration;
import org.weixin4j.User;
import org.weixin4j.http.OAuth2Token;
import org.weixin4j.web.AdvancedUtil;

import com.common.CommonUtil;
import com.common.ResultData;
import com.filter.BaseController;

import beans.user.agentxh;
import beans.user.order;
import beans.user.user;
import beans.user.xh;
import service.user.AgentXHServiceImpl;
import service.user.WXUserServiceImpl;
import service.user.XHServiceImpl;
@Controller
@RequestMapping("/wx")
public class BindXHController extends BaseController{

	@Resource
	private WXUserServiceImpl<user> wxUserServiceImpl;
	@Resource
	private AgentXHServiceImpl<agentxh> agentXHServiceImpl;
	@Resource
	private XHServiceImpl<xh> xHServiceImpl;

	@RequestMapping("/bindxh")
	public String payindex() throws Exception {
		String code = getReq().getParameter("code");
		if(null != code && !"".equals(code)){
			System.out.println(code);
			//根据code换取openId
			OAuth2Token oa = AdvancedUtil.getOauth2AccessToken(Configuration.getOAuthAppId(), Configuration.getOAuthSecret(),code);
			if(!"".equals(oa) && null != oa){
				user temUser = wxUserServiceImpl.queryById(oa.getOpenid());
				if(temUser==null) {
					User u = AdvancedUtil.getSNSUserInfo(oa.getAccess_token(), oa.getOpenid());
					temUser = new user();
					temUser.setId(UUID.randomUUID().toString());
					temUser.setOpenid(oa.getOpenid());
					temUser.setCity(u.getCity());
					temUser.setCountry(u.getCountry());
					temUser.setGroupid(u.getGroupid());
					temUser.setHeadimgurl(u.getHeadimgurl());
					temUser.setLanguage(u.getLanguage());
					temUser.setNickname(u.getNickname());
					temUser.setProvince(u.getProvince());
					temUser.setRemark(u.getRemark());
					temUser.setSex(String.valueOf(u.getSex()));
					temUser.setSubscribe(u.getSubscribe());
					temUser.setSubscribe_time(new Date(u.getSubscribe_time()*1000L));
					temUser.setQr_scene_str(u.getQr_scene_str());
					wxUserServiceImpl.add(temUser);

					getReq().getSession().setAttribute("wxuser", temUser);
				}
				else
					getReq().getSession().setAttribute("wxuser", temUser);
				return "wechat/home/bindxh";
			}else{//登录失败
				return "wechat/home/noright";
			}
		}
		else {
			//user temUser2 = wxUserServiceImpl.queryById("oczs10h9XzVnILn-V84n2Q-mcfns");
			//getReq().getSession().setAttribute("wxuser", temUser2);
			user user = (user) getReq().getSession().getAttribute("wxuser");
			if(user==null) {
				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Configuration.getOAuthAppId()+"&redirect_uri=http%3a%2f%2f2.zydkj.net.cn%2fwx%2fbindxh&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect";
			}

			return "wechat/home/bindxh";
		}
	}

	@RequestMapping("/savebindxh")
	@ResponseBody
	public void savebindxh(String xh) {
		ResultData<String> rd = new ResultData<>();

		agentxh _agentxh = agentXHServiceImpl.getByXH(xh);
		if(_agentxh==null) {
			rd.setMessage("当前序号不存在!");
			responseJson(rd);
			return;
		}
		if(!_agentxh.getStatus().equals("1")) {
			rd.setMessage("当前序号已经被使用了!");
			responseJson(rd);
			return;
		}
		user user = (user) getReq().getSession().getAttribute("wxuser");
		_agentxh.setStatus("2");
		_agentxh.setWxopenid(user.getOpenid());
		_agentxh.setPaytime(new Date());
		try {
			agentXHServiceImpl.update(_agentxh);//更新序号状态

			//增加用户时间
			xh temXh = xHServiceImpl.getByUserid(user.getOpenid());
			if(temXh!=null) {
				temXh.setTotalcount(temXh.getTotalcount()+_agentxh.getUsecount());
				temXh.setLastcount(temXh.getLastcount()+_agentxh.getUsecount());
				temXh.setXh(_agentxh.getNum());

				Calendar cal = Calendar.getInstance();
				cal.setTime(temXh.getLasttime());
				cal.add(Calendar.DATE, _agentxh.getUsetime());
				temXh.setLasttime(cal.getTime());
				xHServiceImpl.updateTotalCount2(temXh);
			}
			else {
				xh _xh = new xh();
				_xh.setAddtime(new Date());
				_xh.setId(UUID.randomUUID().toString());
				_xh.setUid(user.getOpenid());
				_xh.setXh(_agentxh.getNum());
				_xh.setLastcount(_agentxh.getUsecount());
				_xh.setTotalcount(_agentxh.getUsecount());

				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DATE, _agentxh.getUsetime());
				_xh.setLasttime(cal.getTime());
				xHServiceImpl.add(_xh);
			}
			rd.setType(1);
		} catch (Exception e) {
			e.printStackTrace();
		}

		responseJson(rd);
	}
}
